package com.foreveross.bsl.push.application.impl.channel;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;

@Component
public class DefaultChannelSelector implements ChannelSelector, ApplicationContextAware, DisposableBean {

	private final Logger log = LoggerFactory.getLogger(this.getClass());
	private final Map<String, PushChannelable> pushChannelMap = Maps.newHashMap(); // hashTable才是安全的

	@Override
	public PushChannelable selectChannel(String channelId) throws ChannelNotFoundException{
		final PushChannelable channel = this.pushChannelMap.get(channelId);
		if(channel == null)
			throw new ChannelNotFoundException(channelId+" channel not found");
		return channel;
	}

	/** web容器启动时，上下文会自动加载调用
	 * [setApplicationContext description]
	 * @param  appCtx         [description]
	 * @throws BeansException [description]
	 */
	@Override
	public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
		Map<String, PushChannelable> channels = appCtx.getBeansOfType(PushChannelable.class);// 根据Bean得到所有的对象 包括子类实现类
		for(PushChannelable channel : channels.values()) {
			this.pushChannelMap.put(channel.getChannelId(), channel);
		}
		log.info("可用的推送渠道有{}个:{}", channels.size(), this.pushChannelMap.keySet());
	}

	@Override
	public void destroy() throws Exception {
		for(String key : this.pushChannelMap.keySet()){
			this.pushChannelMap.get(key).close();
		}
	}
}
